<template>
	<view class="gmgl">
		<headertop title="过敏日记" str="orderlist" str1="oridei" :back1="back1"></headertop>
		<view class="gmglback">
		</view>
		<view class="" :style="{'margin-top':statusBarHeight+'px','width':'100%','height':barHeight+'px'}">
		</view>
		<view class="rili">
			<image :src="typestr!='week'? _static('/images/Union@2x.png'):_static('/images/guanbiimg.png')"
				class="riliback" mode="widthFix"></image>
			<week-fold-calendar activeBgColor="#2AB4F5" @qiehuan="qiehuan" @openfun="openfun" @change="change"
				:dots="dots" :custom-style="customStyle" active-color="#fff"></week-fold-calendar>
		</view>
		<view class="formsbox">
			<view class="center">
				<view class="line1">
					<span style="color: #1D2129;">日期：</span>
					<span style="color: #4E5969">{{formattedDate}}</span>
				</view>
				<view class="line">
					<span style="color: #1D2129;"><span style="color: #F53F3F;">*</span>请选择是否过敏：</span>
					<view class="rightt" @click="show=true">
						<span style="color: #4E5969" v-if="!formData['is_allergy']">请选择</span>
						<span style="color: #4E5969" v-else>{{text(is_allergyarr,formData['is_allergy']) }}</span>
						<image :src="_static('/images/Frjt.png')" class="rightarrow" mode="">
						</image>
					</view>

				</view>
				<view class="gmqk">
					<view class="title">
						过敏情况：
					</view>
					<view class="shurk">
						<textarea cursor-spacing="100" v-model="formData['text']" placeholder="请输入内容" id="" cols="30"
							rows="10"></textarea>
					</view>
				</view>
				<view class="sctp">
					<view class="title">
						上传图片
					</view>
					<view class="images">
						<view class="image" @click.stop="previewImage(index,images)" v-for="(item,index) in images"
							:key="index">
							<image :src="item" mode=""></image>
							<image :src="_static('/images/删除.png')" @click.stop="shanchu(images,index)" class="remivon"
								mode=""></image>
						</view>
						<view class="uploadimg" v-if="images.length!=3" @click="uploadImage('images')">
							<image :src="_static('/images/Group 10221@2x.png')" class="addicon" mode="">
							</image>
						</view>
					</view>
					<view class="tshiyu">支持格式：JPG、PNG、单个文件不能超过2m</view>
				</view>
			</view>
		</view>
		<view class="" style="height: 230rpx;">

		</view>
		<view class="fixed">
			<view class="btn" @click="tj1">
				提交
			</view>
		</view>
		<up-popup :show="show" mode="bottom">
			<view class="back">
				<view class="xuanxiang">
					<view class="tt" style="margin-left: 30rpx;color: #888;" @click="show=false">
						取消
					</view>
					<view class="tt" style="font-weight: 600;">
						请选择是否过敏
					</view>
					<view class="tt" style="margin-right: 30rpx;color: #0077BE;" @click="queding">
						确认
					</view>
				</view>
				<picker-view immediate-change="true" :indicator-style="indicatorStyle"
					:value="zhuanind(is_allergyarr,formData.is_allergy )" @change="bindChange" class="picker-view">
					<picker-view-column>
						<view class="item" v-for="(item,index) in is_allergyarr" :key="index">
							{{item['title']}}
						</view>
					</picker-view-column>
				</picker-view>
			</view>
		</up-popup>
	</view>
</template>
<script setup>
	import WeekFoldCalendar from '@/components/week-fold-calendar1/week-fold-calendar.vue';
	import {
		onPageScroll,
		onLoad,
		onShow,
		onReachBottom
	} from "@dcloudio/uni-app";
	import {
		ref,
		reactive,
		onMounted
	} from 'vue'
	import ulm, {
		$api
	} from '@/ulm';
	import headertop from '@/components/header.vue'
	import {
		_static
	} from '@/ulm/utils/url.js'
	import {
		getToken
	} from '@/ulm/utils/auth.js'
	import {
		baseUrl
	} from '@/ulm/config';
	const dots = ref([])
	const value1 = ref(0)
	const indicatorStyle = ref(`height: 40px`)
	const show = ref(false)
	const dateobj = reactive({
		start_date: '',
		end_date: ''
	})
	const customStyle = ref({
		fontSize: '28rpx',
		color: '#1D2129',
		fontWeight: 'normal',
		background: '#F7F8FA',
	})
	const formattedDate = ref('')
	const statusBarHeight = ref('')
	const barHeight = ref('')
	const back1 = ref('')
	const typestr = ref('')
	const is_allergyarr = ref([{
		title: '否',
		id: '0'
	}, {
		title: '是',
		id: '1'
	}])
	const images = ref([])
	const is_allergy = ref('')
	const formData = reactive({
		date: '',
		is_allergy: '',
		text: '',
		images: '',
		id: undefined
	})

	function zhuanind(arr, ite) {
		console.log(arr, ite, 'arrite---------');
		var ind = arr.findIndex(item => item['id'] == ite)
		console.log(ind, 'ind--------------------');
		if (ind == -1) {
			ind = 0
		}
		return [ind]
	}

	function previewImage(index, arr) {
		wx.previewImage({
			current: arr[index], // 当前显示图片的http链接
			urls: arr // 需要预览的图片http链接列表
		});
	}

	function tj1() {
		formData['date'] = formattedDate.value
		if (images.value.length) {
			formData['images'] = images.value.join()
		} else {
			formData['images'] = ''
		}
		for (var i in formData) {
			if (i != 'id' && i != 'images' && i != 'text') {
				if (!formData[i]) {
					uni.showToast({
						title: '必填项不能为空',
						icon: 'none'
					})
					return
				}
			}
		}
		uni.showModal({
			title: '提示', // 标题（可选）
			content: '是否确认提交', // 内容（可选）
			confirmText: '确定', // 确认按钮文字（可选，默认“确定”）
			success: (res) => {
				if (res.confirm) {
					// 执行确定后的逻辑
					tj()
				}
			},
			fail: (err) => {}
		});
	}

	async function tj() {
		const res = await $api.allergy_diary(formData)
		if (res.code == 1) {
			formData['date'] = ''
			formData['is_allergy'] = ''
			formData['text'] = ''
			formData['images'] = ''
			images.value = []
			setTimeout(() => {
				uni.showToast({
					title: '提交成功',
					icon: 'none'
				})
			}, 500)
			init()
		} else {
			uni.showToast({
				title: res.msg,
				icon: 'none'
			})
		}
	}

	function text(arr, item) {
		var ind = arr.findIndex(ite => ite.id == item)
		if (ind == -1) {
			return ''
		} else {
			return arr[ind]['title']
		}
	}
	onMounted(() => {
		statusBarHeight.value = uni.getSystemInfoSync().statusBarHeight
		const {
			top,
			height
		} = wx.getMenuButtonBoundingClientRect();
		barHeight.value = height ? height + (top - statusBarHeight.value) * 2 : 38;
	})

	function uploadImage(str) {
		uni.chooseImage({
			count: 3 - images.value.length, // 最多可选择图片数量
			sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图
			sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机
			success: (res) => {
				const validImages = res.tempFiles.filter(file => {
					return file.size <= 2 * 1024 * 1024; // 2MB = 2 * 1024 * 1024 Bytes
				});
				if (validImages.length === 0) {
					uni.showToast({
						title: `${res.tempFiles.length - validImages.length}张图片超过2MB`,
						icon: 'none'
					});
					return;
				}
				console.log(res, 'res-------');
				// tempFilePath 可以作为 img 标签的 src 属性显示图片
				const tempFilePaths = res.tempFilePaths
				uploadImages(tempFilePaths, str)
			},
			fail: (err) => {
				console.log('选择图片失败', err)
			}
		})
	}

	function uploadImages(filePaths, str) {
		const uploadTasks = filePaths.map((filePath, index) => {
			console.log(filePath, 'filePath===========');
			return new Promise((resolve, reject) => {
				uni.uploadFile({
					url: `${baseUrl}/api/common/upload`,
					filePath: filePath,
					name: 'file',
					formData: {
						index: index // 可以添加序号标识
					},
					header: {
						token: getToken()
					},
					success: (uploadRes) => {
						resolve(JSON.parse(uploadRes.data))
					},
					fail: (err) => {
						reject(err)
					}
				})
			})
		})
		uni.showLoading({
			title: '上传中...'
		})
		Promise.all(uploadTasks)
			.then(results => {
				console.log(results[0], 'results[0]results[0]results[0]');
				for (var i in results) {
					images.value.push(results[i]['data']['fullurl'])
				}
				uni.hideLoading()

				uni.showToast({
					title: `成功上传${results.length}张图片`,
					icon: 'success'
				})
			})
			.catch(err => {
				console.log('部分图片上传失败', err)
				uni.hideLoading()

			})
	}

	function bindChange(e) {
		const val = e.detail.value
		is_allergy.value = is_allergyarr.value[val[0]]['id']
		console.log(is_allergy.value, 'is_allergy.valueis_allergy.valueis_allergy.valueis_allergy.value');
	}


	function queding() {
		if (!is_allergy.value) {
			formData.is_allergy = is_allergyarr.value[0]['id']
		} else {
			formData.is_allergy = is_allergy.value
		}
		show.value = false
	}


	function shanchu(arr, i) {
		arr.splice(i, 1)
	}

	function qiehuan(e) {
		var riqi = e + ''
		var arr = riqi.split('-')
		dateobj['start_date'] = `${arr[0]}-${arr[1]}-01`
		dateobj['end_date'] = `${arr[0]}-${arr[1]}-${getDaysInMonth(arr[0],arr[1])}`
		// formattedDate.value = `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`
		init()
	}

	onPageScroll((e) => {
		if (e.scrollTop > 100) {
			back1.value = '#81D6FF'
		} else {
			back1.value = ''
		}
	})

	function getDaysInMonth(year, month) {
		// 注意：month参数是0-11（0表示一月，11表示十二月）
		var dayy = new Date(year, month + 1, 0).getDate();
		if (dayy < 10) {
			return '0' + dayy
		} else {
			return dayy
		}
	}

	onLoad(() => {
		// 获取当前日期和时间
		const now = new Date();
		// 获取年月日
		const year = now.getFullYear();
		const month = now.getMonth() + 1; // 月份从0开始，需要+1
		const day = now.getDate();
		dateobj['start_date'] = `${year}-${month}-01`
		dateobj['end_date'] = `${year}-${month}-${getDaysInMonth(year,month)}`
		formattedDate.value = `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`
		init()
	})
	async function init() {
		const res = await $api.dateList(dateobj)
		if (res.code == 1) {
			var arr = []
			for (var i in res.data) {
				var obj = {
					date: res.data[i],
					value: 1
				}
				arr.push(obj)
			}
			dots.value = arr
			console.log(dots.value, 'dots.valuedots.valuedots.value');
			userdetailinit()
		}
	}
	async function userdetailinit() {
		const res = await $api.userdetail({
			date: formattedDate.value
		})
		if (res.code == 1) {
			if (!res.data) {
				formData['date'] = ''
				formData['is_allergy'] = ''
				formData['text'] = ''
				formData['images'] = ''
				images.value = []
				return
			}
			formData.date = res.data.date
			formData.is_allergy = res.data.is_allergy
			formData.text = res.data.text
			formData.id = res.data.id
			if (res.data.images) {
				images.value = res.data.images.split(',')
			} else {
				images.value = []
			}
		}
	}

	function change(date) {
		formattedDate.value = date
		userdetailinit()
	}

	function openfun(e) {
		typestr.value = e
		console.log(e, typestr.value, 'eeeeeeeeeeeeeeee');
	}
</script>

<style lang="scss">
	.textarea {
		font-size: 28rpx;
	}

	.back {
		background: #FFFFFF;
		width: 100%;
		overflow: hidden;
		border-radius: 30rpx 30rpx 0 0;

		.xuanxiang {
			width: 100%;
			display: flex;
			align-items: center;
			margin-top: 30rpx;
			overflow: hidden;
			justify-content: space-between;
			margin-bottom: 30rpx;
			background: #FFFFFF;

			.tt {
				font-size: 32rpx;
			}
		}

	}

	.picker-view {
		width: 100%;
		height: 600rpx;
		margin-top: 20rpx;
		background: #FFFFFF;
		border-radius: 20rpx 20rpx 0 0;
	}

	.item {
		line-height: 100rpx;
		text-align: center;
	}

	::v-deep .u-popup__content {
		border-radius: 20rpx 20rpx 0 0;
	}


	.fixed {
		width: 100%;
		height: 194rpx;
		background: #FFFFFF;
		box-shadow: 0rpx -6rpx 14rpx 0rpx rgba(0, 0, 0, 0.03);
		border-radius: 0rpx 0rpx 0rpx 0rpx;
		position: fixed;
		bottom: 0%;
		z-index: 9999;

		.btn {
			width: 686rpx;
			height: 82rpx;
			background: #2AB4F5;
			border-radius: 12rpx 12rpx 12rpx 12rpx;
			text-align: center;
			line-height: 82rpx;
			font-family: PingFang SC, PingFang SC;
			font-weight: 500;
			font-size: 32rpx;
			color: #FFFFFF;
			margin: auto;
			margin-top: 32rpx;
		}
	}

	page {
		background: #F7F8FA;
	}

	.gmgl {
		width: 100%;
		overflow: hidden;
		position: relative;

		.gmglback {
			width: 100%;
			height: 450rpx;
			background: linear-gradient(180deg, #CAEEFF 71%, rgba(240, 250, 255, 0) 100%);
			border-radius: 0rpx 0rpx 0rpx 0rpx;
			position: absolute;
			z-index: -1;
		}

		.formsbox {
			width: 686rpx;
			margin: auto;
			margin-top: 28rpx;
			background: #FFFFFF;
			box-shadow: 0rpx 4rpx 10rpx 0rpx rgba(0, 0, 0, 0.03);
			border-radius: 24rpx 24rpx 24rpx 24rpx;
			overflow: hidden;

			.center {
				width: 630rpx;
				margin: auto;
				overflow: hidden;

				.line1 {
					width: 100%;
					height: 92rpx;
					display: flex;
					align-items: center;
					justify-content: space-between;
					font-size: 28rpx;
					border-bottom: 2rpx solid #F2F3F5;
				}

				.sctp {
					width: 100%;
					overflow: hidden;
					border-top: 2rpx solid #F2F3F5;
					margin-top: 28rpx;

					.title {
						font-family: PingFang SC, PingFang SC;
						font-weight: 400;
						font-size: 28rpx;
						color: #1D2129;
						margin-top: 24rpx;
					}

					.tshiyu {
						font-family: PingFang SC, PingFang SC;
						font-weight: 400;
						font-size: 24rpx;
						color: #86909C;
						margin-top: 16rpx;
						margin-bottom: 20rpx;
					}

					.images .image:nth-child(3) {
						margin-right: 0rpx;
					}

					.images {
						width: 100%;
						margin-top: 20rpx;
						display: flex;
						align-items: center;
						flex-wrap: wrap;

						.image {
							width: 224rpx;
							height: 174rpx;
							border-radius: 16rpx 16rpx 16rpx 16rpx;
							position: relative;
							margin-right: 30rpx;
							margin-bottom: 20rpx;

							image {
								width: 224rpx;
								height: 174rpx;
								border-radius: 16rpx 16rpx 16rpx 16rpx;
								overflow: hidden;
							}

							.remivon {
								position: absolute;
								width: 30rpx;
								height: 30rpx;
								top: -6%;
								right: -6%;
								z-index: 9999;
							}
						}

						.uploadimg {
							width: 224rpx;
							height: 174rpx;
							display: flex;
							align-items: center;
							justify-content: center;
							background: #F7F8FA;
							border-radius: 16rpx 16rpx 16rpx 16rpx;
							margin-right: 30rpx;
							margin-bottom: 10rpx;

							image {
								width: 62rpx;
								height: 62rpx;
							}
						}
					}
				}

				.gmqk {
					width: 100%;
					overflow: hidden;

					.title {
						font-family: PingFang SC, PingFang SC;
						font-weight: 400;
						font-size: 28rpx;
						color: #1D2129;
						margin-top: 24rpx;
					}

					.shurk {
						width: 630rpx;
						height: 174rpx;
						background: #F7F8FA;
						border-radius: 16rpx 16rpx 16rpx 16rpx;
						overflow: hidden;
						margin-top: 24rpx;

						textarea {
							width: 580rpx;
							margin-top: 24rpx;
							margin-left: 24rpx;
							height: 150rpx;
							font-size: 24rpx;
						}
					}
				}

				.line {
					width: 100%;
					height: 88rpx;
					display: flex;
					align-items: center;
					justify-content: space-between;
					font-size: 28rpx;
					border-bottom: 2rpx solid #F2F3F5;

					.rightt {
						display: flex;
						align-items: center;

						.rightarrow {
							width: 24rpx;
							height: 24rpx;
						}

					}
				}
			}
		}

		.rili {
			width: 686rpx;
			overflow: hidden;
			margin: auto;
			position: relative;
			margin-top: 32rpx;

			.riliback {
				width: 100%;
				height: 678rpx;
				position: absolute;
				// box-shadow: 0rpx 4rpx 10rpx 0rpx rgba(0, 0, 0, 0.03);
			}
		}
	}
</style>